<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use EasyWeChat;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use App\Http\Controllers\Admin\BaseController;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Order as payOrder;
use Illuminate\Support\Facades\Redis;
use App\Models\Company;
use Carbon\Carbon;
use Illuminate\Http\Response;
use Log;

class PayController extends BaseController
{

    public function cashier()
    {
        $payOrder = payOrder::where('corpid', $this->corpid)->get();
        return view('/sysadmin/company-vip')->with('user', $this->user)->with('company', $this->company)->with('payOrder', $payOrder);
    }

    public function wechat_buy()
    {
        $wechat_user = session('wechat.oauth_user');
        // 创建订号
        $order_id = date("YmdHis", time()) . "00" . $this->user->id . get_rnd_num(2);
        $is_weixin=$this->is_weixin();

        return view('/sysadmin/buy-vip')->with('user', $this->user)->with('wechat_user', $wechat_user)->with('order_id', $order_id)->with('company', $this->company)->with('is_weixin', $is_weixin);
    }

    private  function is_weixin(){

        if ( strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false ) {
            return true;
        }
        return false;
    }

    public function wechat_native_buy()
    {
        return view('/pc_sysadmin/buy-vip')->with('user', $this->user)->with('company', $this->company);
    }

    public function cashier_native()
    {
        $payOrder = payOrder::where('corpid', $this->corpid)->get();
        return view('/pc_sysadmin/company-vip')->with('user', $this->user)->with('company', $this->company)->with('payOrder', $payOrder);
    }

    public function wechat_native_pay(Request $request)
    {

        $name = $request->input('name');
        $corpid = $request->input('corpid');
        $detail = $request->input('detail');
        $price = [1 => 0.888, 2 => 1.888, 3 => 2.888];
        $price = $price[$request->input('price', '1')];
        $goods_type = $request->input('price', '1');
        $price = 0.01;
        // 初始化
        $app = new Application(config('wechat'));
        $payment = $app->payment;

        // 创建订号
        $order_id = date("YmdHis", time()) . "00" . $this->user->id . get_rnd_num(2) . 'kpi';
        //支付信息
        $attributes = [
            'trade_type' => 'NATIVE',
            'out_trade_no' => $order_id,
            'body' => $name,
            'detail' => $detail,
            'total_fee' => $price * 100,
            'notify_url' => 'http://www.cimo.net/pay_validate',
        ];
        // 创建订单
        $order = new Order($attributes);
        //统一下单
        $result = $payment->prepare($order);
        //入库
        $this->orderSave($attributes, 'wechat', $this->user->id, $goods_type, $this->corpid);

        //二维码生成输出
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $paycade = QrCode::size(250)->generate($result['code_url']);
            return view('pc_sysadmin.pay')->with('paycade', $paycade)->with('price', $price)->with('name', $name)->with('order_sn', $order_id);
        } else {
            echo $result->err_code_des;
        }
    }
    //入库

    protected function orderSave($order, $pay_type, $user_id, $goods_type, $corpid)
    {
        //入库
        $kpi_order = array(
            'total_fee' => $order['total_fee'],
            'out_trade_no' => $order['out_trade_no'],
            'body' => $order['body'],
            'detail' => $order['detail'],
            'pay_type' => $pay_type,
            'user_id' => $user_id,
            'corpid' => $corpid,
            'goods_type' => $goods_type,
            'status' => 0,
        );
        Redis::hset('kpi_order', $order['out_trade_no'], json_encode($kpi_order));
    }


    //移到没基类的类中

    public function wechat_h5_pay(Request $request)
    {
        $name = $request->input('name');
        $corpid = $request->input('corpid');
        $detail = $request->input('detail');
        $price = [1 => 0.888, 2 => 1.888, 3 => 2.888];
        $price = $price[$request->input('price', '1')];
        $goods_type = $request->input('price', '1');
        $price = 0.01;
        // 初始化
        $app = new Application(config('wechat'));
        $payment = $app->payment;

        // 创建订号
        $order_id = date("YmdHis", time()) . "00" . $this->user->id . get_rnd_num(2) . 'kpi';
        //支付信息
        $attributes = [
            'trade_type' => 'MWEB',
            'out_trade_no' => $order_id,
            'body' => $name,
            'detail' => $detail,
            'total_fee' => $price * 100,
            'notify_url' => 'http://www.cimo.net/pay_validate',
        ];
        // 创建订单
        $order = new Order($attributes);
        //统一下单
        $result = $payment->prepare($order);
        //入库
        $this->orderSave($attributes, 'wechat', $this->user->id, $goods_type, $this->corpid);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $mweb_url = $result->mweb_url;

            return view('molliepay')->with('mweb_url', $mweb_url)->with('price', $price)->with('name', $name)->with('detail', $detail);
        } else {
            echo $result->err_code_des;
        }
    }

    public function pay_validate(Request $Request)
    {
        Log::notice($Request);
        Log::notice('ssss1');
        $app = new Application(config('wechat'));
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            Redis::hset('kpi_order_pay_error', $notify->out_trade_no, json_encode($notify));
            if (substr($notify->out_trade_no, -3) == 'kpi') {
                if ($successful) {
                    Redis::hset('kpi_order_pay_status', $notify->out_trade_no, json_encode($notify));
                    $kpi_key = $notify->out_trade_no;
                    $order = json_decode(Redis::hget('kpi_order', $kpi_key));
                    $pay_order = new payOrder;
                    //订单信息
                    $pay_order->user_id = $order->user_id;
                    $pay_order->order_sn = $order->out_trade_no;
                    $pay_order->goods_type = $order->goods_type;   //3种中的哪一种
                    $pay_order->pay_status = 1;
                    $pay_order->pay_type = $order->pay_type;
                    $pay_order->goods_name = $order->body;
                    $pay_order->corpid = $order->corpid;
                    //支付信息
                    $pay_order->sign = $notify->sign;
                    $pay_order->time_end = $notify->time_end;
                    $pay_order->total_fee = $notify->total_fee / 100;
                    $pay_order->transaction_id = $notify->transaction_id;
                    $pay_order->save();
                    //修改续费时间
                    $this->add_expiry($order->corpid, $order->goods_type);

                } else {
                    Redis::hset('kpi_order_pay_error', $notify->out_trade_no, json_encode($notify));
                    //支付失败
                }
                return true;
            }
        });
        return $response;
    }

    private function add_expiry($corpid, $type)
    {
        $Company = Company::where('id', $corpid)->first();
        $now = Carbon::now();
        $expire = Carbon::parse($Company->expire_at);
        if ($now->gte($expire)) {
            $Company->expire_at = $now->modify('+' . $type . 'year');
        } else {
            $Company->expire_at = $expire->modify('+' . $type . 'year');
        }
        $Company->save();
    }

    public function pay_check(Request $Request)
    {
        $sn = $Request->input('sn');
        $bool = payOrder::where('order_sn', $sn)->where('pay_status', 1)->first();
        if ($bool) {
            return $this->formatJson('success', '支付成功');
        } else {
            return $this->formatJson('false', '还未支付');
        }
    }
}
